package com.fanketly.musicdiary.data.network

import com.fanketly.musicdiary.data.model.SongInfo
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.coroutines.flow.flow
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query
import javax.inject.Inject
import javax.inject.Singleton

private interface RetrofitNetworkApi {

    @GET(value = "musicInfo")
    suspend fun getMusicInfo(@Query("mood") mood: String): SongInfo
}

//模拟器Wifi中的网关地址
private const val BaseUrl = "http://172.17.100.2:8080"

//@Serializable
//private data class NetworkResponse<T>(
//    val data: T
//)

@Singleton
class RetrofitNetwork @Inject constructor(
    networkJson: Json
) {
    private val networkApi = Retrofit.Builder().baseUrl(BaseUrl).client(
        OkHttpClient.Builder().addInterceptor(
            HttpLoggingInterceptor().apply {
                setLevel(HttpLoggingInterceptor.Level.BODY)
            }).build()
    )
//        .addConverterFactory(GsonConverterFactory.create())
        .addConverterFactory(networkJson.asConverterFactory("application/json".toMediaType()))
        .build().create(RetrofitNetworkApi::class.java)

    suspend fun getMusicInfo(mood: String) = flow<SongInfo?> {
        //如果请求失败就会被下流的catch捕捉到
        val musicInfo = networkApi.getMusicInfo(mood)
        emit(musicInfo)
    }
}